package mobi.pruss.multiuser;

import java.util.ArrayList;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;

public class Users extends Activity {
	ListView userList;
	ArrayList<String> users;
	private Resources res;
	private boolean quickExit = false;
	private static final String PREF_USERS = "users";
	private static final int MENU_RENAME = 0;
	private static final int MENU_DELETE = 1;
	
	
	private void fatalError(int title, int msg) {
		quickExit = true;
        AlertDialog alertDialog = new AlertDialog.Builder(this).create();
        
        Log.e("fatalError", (String) res.getText(title));

        alertDialog.setTitle(res.getText(title));
        alertDialog.setMessage(res.getText(msg));
        alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, 
        		res.getText(R.string.ok), 
        	new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {finish();} });
        alertDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
            public void onCancel(DialogInterface dialog) {finish();} });
        alertDialog.show();		
	}
	
	private void warning(int title, int msg) {
		quickExit = true;
        AlertDialog alertDialog = new AlertDialog.Builder(this).create();
        
        Log.e("warning", (String) res.getText(title));

        alertDialog.setTitle(res.getText(title));
        alertDialog.setMessage(res.getText(msg));
        alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, 
        		res.getText(R.string.ok), 
        	new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {} });
        alertDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
            public void onCancel(DialogInterface dialog) {} });
        alertDialog.show();		
	}
	
	private void renameUser(int position) {
		@SuppressWarnings("unchecked")
		ArrayAdapter<String> adapter = 
			(ArrayAdapter<String>)(userList.getAdapter());
		
	}
	
	private void saveUsers() {
		StringListPreference.commit(getSharedPreferences(PREF_USERS, 0),users);
	}
	
	private void deleteUser(int position) {
		@SuppressWarnings("unchecked")
		ArrayAdapter<String> adapter = 
			(ArrayAdapter<String>)(userList.getAdapter());
		
		adapter.remove(users.get(position));
		
		saveUsers();
	}
	
	private void addUser(String user) {
		@SuppressWarnings("unchecked")
		ArrayAdapter<String> adapter = 
			(ArrayAdapter<String>)(userList.getAdapter());
		for(int i=0; i<adapter.getCount(); i++) {
			if (user.equals(adapter.getItem(i))) {
				warning(R.string.duplicate_title, R.string.duplicate);
				return;
			}
		}
		adapter.add(user);
		adapter.sort(String.CASE_INSENSITIVE_ORDER);
		saveUsers();
	}
	
	public void onClickAdd(View v) {
        AlertDialog alertDialog = new AlertDialog.Builder(this).create();
        
        alertDialog.setTitle(res.getText(R.string.username_title));
        alertDialog.setMessage(res.getText(R.string.username));
        final EditText input = new EditText(this);
        alertDialog.setView(input);
        alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, 
        		res.getText(R.string.ok), 
        	new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
            	addUser(input.getText().toString());} });
        alertDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
            public void onCancel(DialogInterface dialog) {} });
        alertDialog.show();		
	}
	
	public void onClickApps(View v) {
		startActivity(new Intent(this, Apps.class));
	}
	
	public static ArrayList<String> getUsers(Context c) {
		return StringListPreference.getList(
        		 c.getSharedPreferences(PREF_USERS, 0));
	}
	
	@SuppressWarnings("unchecked")
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        setContentView(R.layout.users);
        if (!Root.test()) {
        	fatalError(R.string.need_root_title, R.string.need_root);
        	return;
        }
        
        res = getResources();
        
        userList = (ListView) findViewById(R.id.users);
        
        users = getUsers(this);        
        
        ArrayAdapter<String> adapter =
        new ArrayAdapter<String>(this, 
        		android.R.layout.simple_list_item_single_choice,
        		users);
        userList.setAdapter(adapter);
        		
        userList.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
        
        registerForContextMenu(userList);
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
    	super.onCreateContextMenu(menu, v, menuInfo);
		menu.setHeaderTitle("Operations");
		menu.add(0,MENU_RENAME,Menu.NONE,"Rename");
		menu.add(0,MENU_DELETE,Menu.NONE,"Delete");
    }
    
    @Override
    public boolean onContextItemSelected(MenuItem item) {
    	int position =  
    		((AdapterView.AdapterContextMenuInfo)item.getMenuInfo()).position;
    	
    	switch(item.getItemId()) {
    	case MENU_DELETE:
    		deleteUser(position);
    		return true;
    	case MENU_RENAME:
    		renameUser(position);
    		return true;
    	default:
    		return false;
    	}
    }
	

}

